const { app, BrowserWindow, Menu, ipcMain, dialog } = require('electron');
const path = require('path');
const axios = require('axios');
const dayjs = require('dayjs');
const async = require('async');
const cheerio = require('cheerio');
const puppeteer = require('puppeteer-core');
require('../electron/common/global_method');
const log = require('../electron/common/log');
const getMenus = require('../electron/config/menus');
const UserModel = require('../electron/business/model/user.model');
const CountModel = require('../electron/business/model/count.model');
const yzAPI = require('../electron/common/yzApi');
const { initRuiKe, signInAccount, loginInAccount, getAccountInfo, editAccountPwd, accountRenew, untieMacCode } = require('../electron/business/modules/rui_ke_funcs.js');

let setting = {};

const methodCallLimit = {
	hourlyLimit: 30, // 每小时最多执行次数
	dailyLimit: 250, // 每天最多执行次数
	userCalls: new Map(), // 存储用户调用数据
};

const userDB = new UserModel();
const countDB = new CountModel();

app.commandLine.appendSwitch('remote-debugging-port', '9222');
app.commandLine.appendSwitch('enable-features', 'NetworkServiceInProcess');
app.commandLine.appendSwitch('ignore-certificate-errors', 'true'); // 忽略证书错误
app.commandLine.appendSwitch('allow-insecure-ssl', '1'); // 允许不安全 SSL

// 原图和显示图的尺寸
const originalWidth = 553; // 原图宽度
const originalHeight = 347; // 原图高度
const displayedWidth = 348; // 显示图宽度
const displayedHeight = 216; // 显示图高度

// 计算缩放比例
const scaleX = displayedWidth / originalWidth;
const scaleY = displayedHeight / originalHeight;
let inputWindow,
	tikTokWindow,
	mcnWindow = null;
let tikTokCookie = '';
let manager1,
	manager2 = null;

let queueIsNull = true;
// 创建一个队列，设置并发数为 10
const queue = async.queue(async function (task) {
	try {
		if (typeof task.fn === 'function') {
			await task.fn(); // 确保 task.fn 是一个函数
		} else {
			throw new Error(`任务 ${task.id} 的 fn 不是一个函数`);
		}
		log.info(`任务 ${task.id} 完成`);
	} catch (err) {
		log.error(`任务 ${task.id} 执行失败:`, err);
		throw err;
	}
}, 10);

queue.drain(async () => {
	queueIsNull = true;
	log.info('队列中的所有任务已完成,重新添加任务');
});

// 用于存储队列中已有的任务 ID
const taskIdsInQueue = new Set();

// 监听队列的错误事件
queue.error((err, task) => {
	console.error(`Error processing task ${task.id}:`, err);
});

// 添加任务到队列的函数
const addTaskToQueue = (id, fn) => {
	log.info(`添加任务 ID: ${id}`);
	taskIdsInQueue.add(id);
	queue.push([{ id, fn }]);
};

if (!app.requestSingleInstanceLock()) {
	app.quit();
} else {
	app.on('second-instance', (event, commandLine, workingDirectory) => {
		if (inputWindow) {
			if (inputWindow.isMinimized()) inputWindow.restore();
			inputWindow.focus();
		}
	});
}

app.whenReady().then(async () => {
	inputWindow = new BrowserWindow({
		width: 1500,
		height: 900,
		webPreferences: {
			preload: path.resolve(__dirname, '../electron/preload.js'),
			contextIsolation: true,
			nodeIntegration: false,
		},
	});
	inputWindow.winId = 'homeWin';
	if (process.env.VITE_DEV_SERVER_URL) {
		inputWindow.loadURL(process.env.VITE_DEV_SERVER_URL);
	} else {
		inputWindow.loadURL(path.resolve(__dirname, '../dist/index.html'));
	}

	Menu.setApplicationMenu(Menu.buildFromTemplate([])); //空菜单

	inputWindow.on('close', () => {
		if (tikTokWindow) tikTokWindow.close(); // 主窗口关闭时强制关闭子窗口
	});

	ipcMain.on('winEvent', (event, type) => {
		if (type == '关闭') {
			inputWindow.close();
		} else if (type == '最小化') {
			inputWindow.minimize();
		}
	});

	ipcMain.on('sendMain', async (event, value) => {
		let data = JSON.parse(value);
		if (data.type == 'createTikTokWindow') {
			await createTikTokWindow();
		} else if (data.type == 'createMcnWindow') {
			await createMcnWindow();
		} else if (data.type == 'setSetting') {
			setting = data.value;
			methodCallLimit.dailyLimit = data.value.one_hour_max;
			methodCallLimit.dailyLimit = data.value.one_day_max;
		} else if (data.type == 'clearAll') {
			return await userDB.clearAll();
		}
	});

	ipcMain.handle('sendMain', async (event, value) => {
		let data = JSON.parse(value);
		if (data.type == 'getUsers') {
			const res = await userDB.searchAll(data.value.search, data.value.page, data.value.pageSize);
			return res;
		} else if (data.type == 'getTotal') {
			const res = await userDB.countAll(data.value.search);
			return res;
		} else if (data.type == 'delUsers') {
			const res = await userDB.batchDelete(data.value);
			return true;
		} else if (data.type == 'clearMcnCache') {
			if (mcnWindow) {
				mcnWindow.webContents.session.clearStorageData({
					storages: ['cookies', 'localstorage', 'sessionstorage', 'indexdb', 'websql'],
				});
				await mcnWindow.close();
				mcnWindow = null;
				return true;
			} else {
				return false;
			}
		} else if (data.type == 'clearTikTokCache') {
			if (tikTokWindow) {
				tikTokWindow.webContents.session.clearStorageData({
					storages: ['cookies', 'localstorage', 'sessionstorage', 'indexdb', 'websql'],
				});
				await tikTokWindow.close();
				tikTokWindow = null;
				return true;
			} else {
				return false;
			}
		} else if (data.type == 'getCountryCounts') {
			const res = await userDB.getCountryCounts();
			return res;
		} else if (data.type == 'getCount') {
			let date = dayjs().format('YYYY-MM-DD');
			const res = await countDB.getCount(date);
			return res;
		}
	});

	inputWindow.webContents.on('before-input-event', (event, input) => {
		if (input.control && input.key === 'F12' && input.type === 'keyDown') {
			inputWindow.webContents.toggleDevTools();
			event.preventDefault();
		}
	});

	ipcMain.on('ruiKe', async (event, value) => {
		let obj = JSON.parse(value);
		// log.info(obj);
		if (obj.type == '登录') {
			try {
				const res = await getAccountInfo(inputWindow, obj.params.loginInAccount_username, obj.params.loginInAccount_userpwd);
				if (res) {
					await loginInAccount(inputWindow, obj.params.loginInAccount_username, obj.params.loginInAccount_userpwd);
				}
			} catch (error) {
				log.info(error);
				return inputWindow.webContents.send('showMessageBox', {
					title: '错误',
					message: '登录超时',
					type: '顶号或到期',
				});
			}
		} else if (obj.type == '注册') {
			await signInAccount(inputWindow, obj.params.signInAccount_username, obj.params.signInAccount_userpwd);
		} else if (obj.type == '充值') {
			await accountRenew(inputWindow, obj.params.accountRenew_cardnumorusername, obj.params.accountRenew_rechcardnum);
		} else if (obj.type == '改密') {
			await editAccountPwd(inputWindow, obj.params.editAccountPwd_username, obj.params.editAccountPwd_userpwd, obj.params.editAccountPwd_newpwd);
		} else if (obj.type == '解绑') {
			await untieMacCode(inputWindow, obj.params.untieMacCode_cardnumorusername);
		}
	});

	await sleep(2000);
	initRuiKe(inputWindow);
	log.success('初始化完成');
});

const createTikTokWindow = async () => {
	if (!tikTokWindow) {
		tikTokWindow = new BrowserWindow({
			width: 1100,
			height: 700,
			webPreferences: {
				nodeIntegration: true,
				contextIsolation: false,
				webSecurity: false,
				partition: 'persist:child-session',
			},
		});

		const childMenu = Menu.buildFromTemplate(getMenus(tikTokWindow));
		tikTokWindow.setMenu(childMenu);
		tikTokWindow.loadURL('https://www.tiktok.com/live');
		tikTokWindow.webContents.on('did-finish-load', async () => {
			log.info('TikTok窗口加载完成');
			log.info(`页面标题: ${tikTokWindow.getTitle()}`);
			const res = await axios.get('http://127.0.0.1:9222/json/list');
			const target = res.data.find((item) => item.type === 'page' && item.title.includes('TikTok 直播推荐内容'));
			puppeteerConnect(target);
		});

		tikTokWindow.webContents.on('did-fail-load', (event) => {
			log.error('TikTok窗口加载失败，重试中...');
			tikTokWindow.loadURL('https://www.tiktok.com/live');
		});

		tikTokWindow.on('close', () => {
			tikTokWindow = null;
			if (manager1) {
				manager1.stop();
				manager1 = null;
			}
			if (manager2) {
				manager2.stop();
				manager2 = null;
			}
		});

		async function puppeteerConnect(target) {
			try {
				if (manager1) return;
				const browser = await puppeteer.connect({
					browserURL: 'http://127.0.0.1:9222' + target.devtoolsFrontendUrl,
					defaultViewport: null,
				});

				const pages = await browser.pages();
				let page = null;
				for (const p of pages) {
					if (p.url().includes('https://www.tiktok.com/') && (await p.title()).includes('TikTok')) {
						page = p;
					}
				}

				await page.setRequestInterception(true);
				page.on('response', async (response) => {
					const url = response.url();
					if (url.includes('/webcast/feed/')) {
						try {
							const data = await response.json();
							if (!data || !data.hasOwnProperty('data')) {
								return;
							}

							let users = [];
							for (const item of data.data) {
								if (!item || !'data' in item || !'owner' in item.data) {
									continue;
								}
								if (item.data.owner.follow_info.follower_count > setting.minFans) {
									if (setting.isShopLive) {
										if (item.data.hashtag?.title.includes('购物')) {
											continue;
										}
									}
									let datetime = dayjs().format('YYYY-MM-DD HH:mm:ss');
									users.push({
										display_id: item.data.owner.display_id,
										room_id: item.data.id_str,
										anchor_id: item.data.owner.id_str,
										sec_uid: item.data.owner.sec_uid,
										following: String(item.data.owner.follow_info.following_count ? item.data.owner.follow_info.following_count : 0),
										followers: String(item.data.owner.follow_info.follower_count ? item.data.owner.follow_info.follower_count : 0),
										audience: String(item.data.user_count ? item.data.user_count : 0),
										tags: item.data.hashtag?.title,
										source: '广场',
										created_at: datetime,
										updated_at: datetime,
									});
								}
							}
							const res = await userDB.batchInsert(users);
							let date = dayjs().format('YYYY-MM-DD');
							await countDB.upsertCount(1, users.length, date);
							// console.log(`采集数量：+${users.length}`);
						} catch (error) {
							log.error('用户数据解析失败：', error.message);
						}
					}
				});
				page.on('request', async (request) => {
					const url = request.url();
					if (url.includes('/webcast/feed/')) {
						if (request.headers()['cookie']) {
							tikTokCookie = request.headers()['cookie'];
						}
					}
					request.continue();
				});

				while (true) {
					if (!tikTokWindow) {
						break;
					}
					await sleep(300);
					// console.log('正在采集中...',page.url())
					if (page.url() == 'https://www.tiktok.com/live') {
						try {
							const btn = await page.waitForSelector('.css-nz9lpk-DivDownButton', { timeout: 30000 });
							await btn.click();
						} catch (error) {
							console.log(error);
							await sleep(30000);
						}
					} else {
						console.log(2);
						await sleep(300000);
						await page.goto('https://www.tiktok.com/live');
					}
				}
			} catch (error) {
				log.error(`创建TikTok窗口失败：${error.message}`);
			}
		}
	}
};

const createMcnWindow = async () => {
	if (!mcnWindow) {
		let isOpen = false;
		mcnWindow = new BrowserWindow({
			width: 1300,
			height: 800,
			webPreferences: {
				nodeIntegration: true,
				contextIsolation: false,
				webSecurity: false,
				sandbox: false,
				resizable: false,
				partition: 'persist:child-session',
			},
		});

		const childMenu = Menu.buildFromTemplate(getMenus(mcnWindow));
		mcnWindow.setMenu(childMenu);
		mcnWindow.loadURL('https://live-backstage.tiktok.com/portal/anchor/relation');

		mcnWindow.on('close', () => {
			mcnWindow = null;
		});

		mcnWindow.webContents.on('did-finish-load', async () => {
			log.info('MCN窗口加载完成');
			log.info(`页面标题: ${mcnWindow.getTitle()}`);
			const res = await axios.get('http://127.0.0.1:9222/json/list');
			const target = res.data.find((item) => item.type === 'page' && item.title.includes('LIVE Backstage'));
			puppeteerConnect(target);
		});

		mcnWindow.webContents.on('did-fail-load', (event) => {
			log.error('MCN窗口加载失败，重试中...');
			mcnWindow.loadURL('https://live-backstage.tiktok.com/portal/anchor/relation');
		});

		async function puppeteerConnect(target) {
			try {
				if (isOpen) return;
				isOpen = true;
				const browser = await puppeteer.connect({
					browserURL: 'http://127.0.0.1:9222' + target.devtoolsFrontendUrl,
					defaultViewport: null,
				});

				const pages = await browser.pages();
				let page = null;
				for (const p of pages) {
					if (p.url().includes('https://live-backstage.tiktok.com/') && (await p.title()).includes('LIVE Backstage')) {
						page = p;
					}
				}
				if (page.url() == 'https://live-backstage.tiktok.com/') return log.error('MCN未登录，请先登录。');

				let result = null;
				const yz = new yzAPI(page);

				page.on('response', async (response) => {
					const url = response.url();
					if (url.includes('blob:https://live-backstage.tiktok.com/')) {
						try {
							const buffer = await response.buffer();
							console.log(buffer);
							const base64String = buffer.toString('base64');
							const text = await yz.findOneBySelector('获取点选验证标题', '.cap-flex.cap-items-center', 5000, 1000);
							const yanZheng = await yz.findOneBySelector('获取验证窗口', '.cap-rounded-lg.cap-cursor-pointer.cap-w-full.cap-h-auto', 5000, 1000);
							const boundingBox = await yanZheng.boundingBox();
							console.log(base64String);
							// const res = await axios.post('http://api.ttshitu.com/predict', {
							// 	username: 'qwer543216',
							// 	password: 'Qwer543216',
							// 	typeid: 27,
							// 	image: base64String,
							// });
							const res = await axios.post('http://www.fdyscloud.com.cn/tuling/predict', {
								username: 'qwer543216',
								password: 'qwer543216',
								b64: base64String,
								version: '3.1.1',
								ID: '07216914',
							});
							console.log(res.data);
							if (res.data.code == 1) {
								// const str = res.data.data.result;
								// const [one, two] = str.split('|');
								// const [oneX, oneY] = one.split(',');
								// const [twoX, twoY] = two.split(',');
								const oneX = res.data.data['点击1']['X坐标值']
								const oneY = res.data.data['点击1']['Y坐标值']
								
								const twoX = res.data.data['点击2']['X坐标值']
								const twoY = res.data.data['点击2']['Y坐标值']
								await page.mouse.click(Number(boundingBox.x) + Math.round(Number(oneX) * scaleX), Number(boundingBox.y) + Math.round(Number(oneY) * scaleX));
								await sleep(2000);
								await page.mouse.click(Number(boundingBox.x) + Math.round(Number(twoX) * scaleY), Number(boundingBox.y) + Math.round(Number(twoY) * scaleY));
								await yz.clickBySelector('确认验证', '::-p-xpath(//div[text()="确认"])', 5000, 5000);
							} else {
								// 重试逻辑
								await yz.clickBySelector('刷新验证', '#captcha_refresh_button', 5000, 5000);
							}
						} catch (error) {
							log.error(`解析点选验证码失败:${error.message}`);
						}
					} else if (url.includes('/batch_check_anchor')) {
						try {
							const data = await response.json();
							let ids = [];
							let anchors = [];
							if (data.data.AnchorList.length > 0 && result) {
								for (const item of data.data.AnchorList) {
									const anchor = result.filter((i) => i.display_id == item.UserBaseInfo.DisplayID);
									if (item.AnchorStatus == 0) {
										if (anchor.length > 0) {
											anchor[0].is_connected = false;
											anchor[0].is_joined = false;
											anchor[0].verification_result = item.CanUseInvitationType[0] == 4 ? '金票' : '普通';
											anchor[0].uploaded_at = dayjs().format('YYYY-MM-DD HH:mm:ss');
											anchor[0].verified_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
										}
										anchors.push(anchor[0]);
									}
									ids.push(anchor[0].id);
								}
								const res = await userDB.batchDelete(ids);
								await axios.post('http://154.38.118.12:16667/api/collect/upload/batchUpload', {
									userName: setting.adminName,
									anchorList: anchors,
								});
								log.success('主播信息上传到服务器成功！');
								let date = dayjs().format('YYYY-MM-DD');
								await countDB.upsertCount(3, anchors.length, date);
								await countDB.upsertCount(2, data.data.AnchorList.length, date);
								console.log(`上传数量：+${anchors.length}`);
							}
						} catch (error) {
							log.error('主播信息上传到服务器错误:', error);
						}
					}
				});

				while (true) {
					log.success('循环中，查询未查验主播数量');
					if (!setting.isVerified) {
						await sleep(20000);
						continue;
					}
					result = await userDB.getUnverified(setting.mcn);
					log.info('当前未查验条数', result.length);
					if (result.length >= 30) {
						if (!trackMethodUsage('mcn')) {
							await sleep(20000);
							continue;
						}
						const names = result.map((user) => user.display_id).join('\n');
						await page.goto('https://live-backstage.tiktok.com/portal/anchor/relation');
						if (!(await yz.clickByEvalSelector('邀请主播_button', '::-p-xpath(//span[text()="邀请主播"])', 5000, 5000))) {
							continue;
						}
						if (!(await yz.inputTypeBySelector('填写主播信息_textarea', names, '::-p-xpath(//textarea[@placeholder="最多可输入 30 位主播，每行一个用户名"])', 5000, 5000))) {
							continue;
						}
						if (!(await yz.clickByEvalSelector('下一步_button', '::-p-xpath(//span[text()="下一步"])', 5000, 5000))) {
							continue;
						}
					}
					await sleep(20000);
				}
			} catch (error) {
				log.error(`MCN窗口错误:${error.message}`);
			}
		}
	}
};

const getCoins = async (id, anchor_id, room_id) => {
	return new Promise(async (resolve, reject) => {
		try {
			console.log('走到了getCoins');
			if (!tikTokCookie) return resolve();
			let res = null;
			let ranks = null;
			var config1 = {
				method: 'get',
				url: `https://webcast.us.tiktok.com/webcast/ranklist/online_audience/?aid=1988&anchor_id=${anchor_id}&app_language=zh-Hans&app_name=tiktok_web&browser_language=zh-CN&browser_name=Mozilla&browser_online=true&browser_platform=Win32&browser_version=5.0%20%28Windows%20NT%2010.0%3B%20Win64%3B%20x64%29%20AppleWebKit%2F537.36%20%28KHTML%2C%20like%20Gecko%29%20tiktok_live_user_caiji%2F1.0.2%20Chrome%2F134.0.6998.44%20Electron%2F35.0.1%20Safari%2F537.36&channel=tiktok_web&cookie_enabled=true&data_collection_enabled=true&device_id=7482780645112153607&device_platform=web_pc&focus_state=true&from_page=user&history_len=2&is_fullscreen=false&is_page_visible=true&os=windows&priority_region=CN&referer=&region=JP&room_id=${room_id}&screen_height=1440&screen_width=3440&tz_name=Asia%2FShanghai&user_is_login=true&webcast_language=zh-Hans`,
				headers: {
					priority: 'u=1, i',
					Cookie: tikTokCookie,
					'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
				},
				timeout: 10000,
			};
			var config2 = {
				method: 'get',
				url: `https://webcast.tiktok.com/webcast/ranklist/online_audience/?aid=1988&anchor_id=${anchor_id}&app_language=zh-Hans&app_name=tiktok_web&browser_language=zh-CN&browser_name=Mozilla&browser_online=true&browser_platform=Win32&browser_version=5.0%20%28Windows%20NT%2010.0%3B%20Win64%3B%20x64%29%20AppleWebKit%2F537.36%20%28KHTML%2C%20like%20Gecko%29%20tiktok_live_user_caiji%2F1.0.2%20Chrome%2F134.0.6998.44%20Electron%2F35.0.1%20Safari%2F537.36&channel=tiktok_web&cookie_enabled=true&data_collection_enabled=true&device_id=7482780645112153607&device_platform=web_pc&focus_state=true&from_page=user&history_len=2&is_fullscreen=false&is_page_visible=true&os=windows&priority_region=CN&referer=&region=JP&room_id=${room_id}&screen_height=1440&screen_width=3440&tz_name=Asia%2FShanghai&user_is_login=true&webcast_language=zh-Hans`,
				headers: {
					priority: 'u=1, i',
					Cookie: tikTokCookie,
					'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
				},
				timeout: 10000,
			};
			res = await axios(config1);
			if (res.data.data.prompts == '请先登录') {
				res = await axios(config2);
			}
			ranks = res.data.data?.ranks;
			let count = 0;
			if (ranks) {
				for (const rank of ranks) {
					count += rank.score;
				}
			}
			if (count < setting.minCoins) {
				await userDB.batchDelete([id]);
			} else {
				await userDB.batchUpdateById([id], { coins: String(count) });
			}
			log.info('获取金币成功', anchor_id, count);
			resolve();
		} catch (error) {
			log.error(`获取金币错误:${error}`);
			resolve();
		}
	});
};

const getUserInfo = async (id, display_id) => {
	return new Promise(async (resolve, reject) => {
		try {
			if (!tikTokCookie) return resolve();
			log.info('https://www.tiktok.com/@' + display_id);
			const result = await axios.get('https://www.tiktok.com/@' + display_id, {
				headers: {
					'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
					cookie: tikTokCookie,
				},
				timeout: 10000,
			});
			const $ = cheerio.load(result.data);
			const scriptTag = $('script#\\__UNIVERSAL_DATA_FOR_REHYDRATION__').html();
			if (JSON.parse(scriptTag).__DEFAULT_SCOPE__['webapp.user-detail'].statusMsg == 'user banned' || JSON.parse(scriptTag).__DEFAULT_SCOPE__['webapp.user-detail'].statusCode != 0) {
				await userDB.batchDelete([id]);
				return resolve();
			}
			log.info('获取地区国家成功');
			let country = JSON.parse(scriptTag).__DEFAULT_SCOPE__['webapp.user-detail'].userInfo.user.region;
			await userDB.batchUpdateById([id], { country: country, region: country });
			resolve();
		} catch (error) {
			log.error(`获取地区国家错误:${error}`);
			await userDB.batchDelete([id]);
			resolve();
		}
	});
};

function trackMethodUsage(userId) {
	const currentTime = Date.now();

	// 获取该用户的调用记录
	if (!methodCallLimit.userCalls.has(userId)) {
		methodCallLimit.userCalls.set(userId, { hourly: [], daily: [] });
	}

	const userRecord = methodCallLimit.userCalls.get(userId);

	// 清除1小时和1天前的记录
	userRecord.hourly = userRecord.hourly.filter((time) => currentTime - time < 3600000); // 3600000ms = 1 hour
	userRecord.daily = userRecord.daily.filter((time) => currentTime - time < 86400000); // 86400000ms = 1 day

	// 判断是否超出限制
	if (userRecord.hourly.length >= methodCallLimit.hourlyLimit) {
		log.error('MCN查验已达到小时调用限制');
		return false;
	}

	if (userRecord.daily.length >= methodCallLimit.dailyLimit) {
		log.error('MCN查验已达到日调用限制');
		return false;
	}

	// 如果没有超出限制，记录调用时间
	userRecord.hourly.push(currentTime);
	userRecord.daily.push(currentTime);

	return true;
}

const startGetCountryAndCoins = async () => {
	log.info('开始获取地区和国家');

	while (true) {
		log.info('循环中', queueIsNull, '是否有任务正在处理：', !queue.idle());
		if (!tikTokCookie) {
			await sleep(5000);
			continue;
		}
		if (!queueIsNull) {
			await sleep(5000);
			continue;
		}
		let taskId = 1;
		const result = await userDB.getCountyOrCoinsNull();
		log.info('国家或金币为空条数：', result.length);
		result.forEach(async (item) => {
			if (item.country == null) {
				addTaskToQueue(taskId, async () => await getUserInfo(item.id, item.display_id));
				taskId++;
			}
			if (item.coins == null) {
				addTaskToQueue(taskId, async () => await getCoins(item.id, item.anchor_id, item.room_id));
				taskId++;
			}
		});
		log.success('添加任务数量：', taskId);
		if (taskId != 1) {
			queueIsNull = false;
		}
		await sleep(5000);
	}
};

startGetCountryAndCoins();
